import {
  insertCart,
  getCartList,
  delCart,
  addCart,
  changeOneGoodsStatus,
  cartAllChange
} from '@/api/cart.js'
export default {
  namespaced: true,
  state: {
    cartList: []
  },
  mutations: {
    // 点击购物车单个添加
    setCartList(state, data) {
      const currentObj = state.cartList.find(
        (item) => item.skuId === data.skuId
      )
      currentObj
        ? (currentObj.count = currentObj.count + data.count)
        : state.cartList.push(data)
    },
    // 全选
    allSelect(state) {
      state.cartList = state.cartList.map((item) => {
        item.selected = !item.selected
        return item
      })
    },
    // 单选框选中状态
    oneChange(state, goods) {
      const obj = state.cartList.find((item) => item.skuId === goods.skuId)
      obj.selected = !obj.selected
    },
    // 删除单个商品
    delGoods(state, goods) {
      const index = state.cartList.findIndex(
        (item) => item.skuId === goods.skuId
      )
      state.cartList.splice(index, 1)
    },
    // 商品数量变化
    changeGoodsNum(state, { goods, num }) {
      const obj = state.cartList.find((item) => item.skuId === goods.skuId)
      obj.count = num
    },
    // 从服务器重新获取购物车数据
    getCartList(state, data) {
      state.cartList = data
    }
  },
  actions: {
    // 添加购物车商品(单个添加)
    async asyncSetCartList({ state, commit, rootState }, data) {
      if (rootState.user.profile.token) {
        // 已登录
        try {
          await addCart({
            skuId: data.skuId,
            count: data.count
          })
          const res = await getCartList() // 获取最新购物车数据
          state.cartList = res
          console.log('添加成功')
        } catch (err) {
          console.log(err.response)
        }
      } else {
        // 未登录
        console.log(data)
        commit('setCartList', data)
      }
    },
    // 单选修改购物车商品选中状态
    async asyncOneChange({ commit, rootState, state }, goods) {
      if (rootState.user.profile.token) {
        // 已登录
        await changeOneGoodsStatus(goods.skuId, {
          selected: !goods.selected,
          count: goods.count
        })
        console.log('修改成功')
        const res = await getCartList() // 获取最新购物车数据
        state.cartList = res
      } else {
        // 未登录
        commit('oneChange', goods)
      }
    },
    // 全选修改购物车商品选中状态
    async asyncAllChange({ commit, rootState, state }, boo) {
      if (rootState.user.profile.token) {
        // 已登录
        await cartAllChange({
          selected: boo,
          ids: state.cartList.map((item) => item.skuId)
        })
        console.log('修改成功')
        const res = await getCartList() // 获取最新购物车数据
        state.cartList = res
      } else {
        // 未登录
        commit('allSelect')
      }
    },
    // 删除单个商品
    async asyncDelGoods({ commit, rootState, state }, goods) {
      if (rootState.user.profile.token) {
        // 已登录
        try {
          await delCart({
            ids: [goods.skuId]
          })
          const res = await getCartList() // 获取最新购物车数据
          state.cartList = res
          console.log('删除成功')
        } catch (err) {
          console.log(err.response)
        }
      } else {
        // 未登录
        commit('delGoods', goods)
      }
    },
    // 修改单选商品数量
    async asyncEditGoodsNum({ commit, rootState }, { goods, num }) {
      if (rootState.user.profile.token) {
        // 已登录
        await changeOneGoodsStatus(goods.skuId, {
          selected: goods.selected,
          count: num
        })
        console.log('修改成功')
        const res = await getCartList() // 获取最新购物车数据
      } else {
        // 未登录
        commit('changeGoodsNum', data)
      }
    },
    // 登录合并购物车数据
    async asyncInsertCart({ state }) {
      if (state.cartList.length) {
        const cartList = state.cartList.map((item) => {
          return {
            skuId: item.skuId,
            selected: item.selected,
            count: item.count
          }
        })
        try {
          console.log(cartList)
          await insertCart(cartList) // 合并购物车到服务器
        } catch (err) {
          console.log(err.response)
        }
        try {
          const res = await getCartList() // 获取最新购物车数据
          state.cartList = res
        } catch (err) {
          console.log('获取购物车数据失败')
        }
      }
    }
  },
  getters: {
    // 计算有效商品列表 isEffective = true  filter
    effectiveList(state) {
      return state.cartList.filter((item) => item.isEffective === true)
    },
    // 已选中列表 selected = true
    selectedList(state, getters) {
      return getters.effectiveList.filter((item) => item.selected)
    },
    // 已选择列表总钱数  selectedList 中所有项的单价*数据进行叠加
    allSelectedPrice(state, getters) {
      return getters.selectedList.reduce((a, c) => a + c.count * c.nowPrice, 0)
    },
    // 全选：有效列表中的seleted字段全为true 才为true
    isAll(state, getters) {
      return getters.effectiveList.every((item) => item.selected)
    }
  }
}
